<template>
  <el-tree
    :data="groupTreeData"
    :show-checkbox="showCheckbox"
    node-key="id"
    default-expand-all
    :expand-on-click-node="false"
    @node-click="nodeClick"
    @node-contextmenu="nodeContextmenu"
    @check="onCheck"
    ref="groupTree"
    :props="defaultProp"
    :render-content="renderContent"
  ></el-tree>
</template>

<script>
export default {
  props: {
    showCheckbox: {
      type: Boolean,
      default: false
    },
    allowEditGroup: {
      type: Boolean,
      default: false
    }
  },
  data() {
    let me = this;
    return {
      groupTreeData: [],
      defaultProp: {
        label: "name"
      }
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    loadData() {
      let me = this;
      me.$http.ajax({
        url: "group/getGroupTree/" + me.$store.state.admin.orgId,
        success(res) {
          me.groupTreeData = res;
        }
      });
    },
    onCheck(data, checkResult) {
      this.$emit("check", data, checkResult);
    },
    nodeClick(data, node, component) {
      this.$emit("node-click", data, node, component);
    },
    nodeContextmenu(event, data, node, component) {
      this.$emit("node-contextmenu", data, node, component);
    },
    setCheckedKeys(keys) {
      this.$refs["resTree"].setCheckedKeys(keys);
    },
    renderContent(h, { node, data, store }) {
      let me = this;
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span v-show={me.allowEditGroup}>
            <el-button
              size="mini"
              type="text"
              on-click={e => this.edit(e, data)}
            >
              编辑
            </el-button>
          </span>
        </span>
      );
    },
    edit(e, data) {
      e.stopPropagation();
      this.$emit("edit-group", data);
    }
  }
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
